package com.hskj.advice;

import cn.hutool.json.JSONUtil;
import com.hskj.dto.ResponseDTO;
import com.hskj.exception.MyException;
import com.hskj.info.PageInfo;
import com.hskj.localUtil.LocalPageUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;

@RestControllerAdvice
public class MyResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        //支持的方法 默认为false 改成true 让当前方法支持所有的类
        return true;
    }
    //错误信息封装
    @ExceptionHandler
    public Object processException(Exception ex){
        if(ex instanceof MyException){
            MyException myException=(MyException)ex;
            return ResponseDTO.error(myException.getCode(),ex.getMessage());
        }
        ResponseDTO dto=ResponseDTO.error(998,ex.getMessage());
        return  dto;
    }

    @Override
    public Object beforeBodyWrite(Object body,
                                  MethodParameter methodParameter,
                                  MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (body instanceof ResponseDTO){
            return body;
        }

        ResponseDTO dto=ResponseDTO.success(body);
        PageInfo pageInfo= LocalPageUtil.get();
        if(pageInfo != null){
            HashMap<Object,Object> map=new HashMap<>();
            map.put("total",pageInfo.getTotal());
            map.put("items",body);
            dto =ResponseDTO.success(map);
            LocalPageUtil.remove();
        }
        if(aClass == StringHttpMessageConverter.class){
            //强转为json字符串
            return JSONUtil.toJsonStr(dto);
        }

        return dto;
    }
}
